import tinymce from 'tinymce/tinymce'
import { isContent, keyTypeMap, isTailNotLast, isAnnex, isTail, isHead } from '@/constants/structure'
import store from '@/store'
import { findLastIndex } from 'lodash'
import { sleep } from '@/utils/helpers'
import { generateAnnexPage, generateContentPage, generateSiblingPage } from '@/utils/parse'
import { contentTypes, isAnnexByType } from '@/constants/structure'
import { typeKeyMap } from '@/constants/structure'
import { v4 as uuid } from "uuid";
import { StdPage } from '../parse/page'
/**
 * 根据节点信息找到节点页面所在位置并添加相应页面
 */

function getNewPageData(newKey) {
  const type = typeKeyMap[newKey]
  // page head: 'cover', 'signature', 'revision', 'contents', 'foreword', 'introduction'
  // page tail: 'annex', 'reference', 'index'
  // content: 'scope', 'design_basis', 'normative_references', 'terms_definitions', 'symbols_abbreviation', 'chapter'
  if (contentTypes.includes(type)) {
    return generateContentPage(type, newKey === 27 ? 'landscape' : 'portrait')
  } else if (['normativeAnnex', 'informativeAnnex'].includes(type)) {
    return generateAnnexPage(type, store.state.xmleditor.editorPageList.filter((i) => isAnnexByType(i.pageType))?.length)
  } else {
    return generateSiblingPage(type)
  }
}

function getNewPagePos(newKey) {
  const nodes = tinymce.activeEditor.dom.select('#tinymce>.page-wrapper .page-sheet')
  const nodeKeys = nodes.map(({ dataset: o }) => keyTypeMap[o.contentPageType || o.annexType || o.pageType])
  let pos = 0
  // 正文的未命名页面
  if (newKey === 26 || newKey === 27) {
    const tailPos = nodeKeys.findIndex(isTail)
    pos = tailPos > -1 ? tailPos - 1 : nodeKeys.length - 1
  } else if (isContent(newKey)) {
    // scope
    if (newKey === 21) {
      pos = nodeKeys.findLastIndex(isHead)
    } else {
      // 其他正文
      pos = findLastIndex(nodeKeys, (i) => i && i < newKey)
      if (newKey === 24 && store.getters.isTermDoc) {
        setTimeout(() => addPage(52))
      }
    }
  }

  // annex = 41,42, reference = 51
  if (isTailNotLast(newKey)) {
    const idx1 = findLastIndex(nodeKeys, isAnnex)
    if (idx1 > -1) {
      pos = idx1
    } else {
      pos = findLastIndex(nodeKeys, (i) => !i || isContent(i))
    }
  }
  // index = 52
  if (newKey === keyTypeMap['index']) {
    pos = nodeKeys.length - 1 //中文+英文索引
  }
  if (newKey === keyTypeMap['indexEn']) {
    pos = nodeKeys.length - 1
  }
  if (isHead(newKey)) {
    for (let i = 0; i < nodeKeys.length; i++) {
      if (newKey === 1) {
        pos = 0
        break
      }
      if (nodeKeys[i] < newKey && newKey < nodeKeys[i + 1]) {
        pos = i
        break
      }
    }
  }

  return pos + 1
}

export function addPagesByData(pos, pages) {
  store.commit('xmleditor/SET_ADDED_PAGE', { data: pages, pos })
  tinymce.activeEditor.fire('pageAdd')
  pages.forEach(page => store.commit('xmleditor/ADD_NEW_PAGE_EDITABLE', page.pageId))
  setTimeout(() => store.commit('xmleditor/UPDATE_DOC_STRUCTURE'))
}

function addPageByData(pos, data) {
  store.commit('xmleditor/SET_ADDED_PAGE', { data, pos })
  tinymce.activeEditor.fire('pageAdd')
  store.commit('xmleditor/ADD_NEW_PAGE_EDITABLE', data.pageId)
  setTimeout(() => store.commit('xmleditor/UPDATE_DOC_STRUCTURE'))
}
export async function replacePageByData(pos, data) {
  store.commit('xmleditor/SET_REPLACED_PAGE', { data, pos })
  await sleep()
  const body1 = tinymce.activeEditor.getDoc()?.querySelector(`[data-page-id="${data.pageId}"] .page_body`)
  const body2 = document.querySelector(`[data-page-id="${data.pageId}"] .page_body`)
  body1.innerHTML = body2.innerHTML
  setTimeout(() => store.commit('xmleditor/UPDATE_DOC_STRUCTURE'))
  await sleep()
  tinymce.activeEditor.fire('contentPasted')
}

export default function addPage(newKey) {
  const data = getNewPageData(newKey)
  const pos = getNewPagePos(newKey)
  addPageByData(pos, data)
}
// 新增特殊章节
export  function addSpecialPage(newKey,pageName,variableId) {
  const data = new StdPage({
    pageId: uuid(),
    pageType: 'content',
    pageLayout: 'portrait',
    pageName:"强度分析",
    variableId: variableId,
    blockList: [
      {
        dataType: 'chapter',
        textData: {
          dataId: uuid(),
          contentList: [
            {
              fullContent: pageName,
              content: pageName,
              contentEn: ''
            }
          ]
        }
      }
    ]
  })
  getNewPageData(newKey)
  const pos = getNewPagePos(newKey)
  addPageByData(pos, data);
}